<?php 
class ScraperController extends Controller {
	var $name = "Scraper";
	var $uses = array('Product', 'Category');
	var $components = array('AmazonECS', 'Utils');
	
	function postToTwitter() {
		//APP::import('Vendor', 'twitter-php/twitter.class');
		
		App::import('Vendor', 'twitter-php', array('file' => 'twitter-php'.DS.'twitter.class.php'));
		$option = array(
			'consumerKey' => 'S3QKJp2rsaIiPwTxwjlRQA',
			'consumerSecret' => 'r27GPyQtEmUnitFhJP4mqbk8CvMxcqXyuHV90XmutHA',
			'accessToken' => ' 	50920508-Tb1Ha4WqAETYUWpdDsTUvsczrRdBc5GuzAp0mcQvz',
			'accessTokenSecret' => 'TwYwcukPVjfAHcGSoR1qMY5Wec4F2MJEzKaclKS5SU'
		);
		$twitter = new Twitter($option['consumerKey'], $option['consumerSecret'], $option['accessToken'], $option['accessTokenSecret']);
		
		$status = $twitter->send('Quick and easy to get any Video Games with big Black Friday deals http://kinectdancegames.net');
	}
	function updateProduct() {
		$fields = array('Category.id');
		$conditions = array('Category.parent_id' => 1);
		$catIds = $this->Category->find('list', array('fields' => $fields, 'conditions' => $conditions));
		
		
		$fields = array('Product.id','Product.asin');
		$conditions = array('Product.is_active' => 0);
		$pIds = $this->Product->find('all', array('fields' => $fields, 'conditions' => $conditions, 'limit' => 2, 'recursive' => -1));
		
		foreach($pIds as $pId) {
			$res = $this->AmazonECS->getProductDetail($pId['Product']['asin']);
			if(isset($res->Items->Item->Offers->TotalOffers) && $res->Items->Item->Offers->TotalOffers >= 1) {
				$features = $res->Items->Item->ItemAttributes->Feature;
				$product_feature = "<ul>";
				if(is_array($features)) {
					foreach($features as $feature) {
						$product_feature .= "<li>" . $feature . "</li>";
					}
				}
				$product_feature .= "</ul>";
				
				$order_link = $res->Items->Item->DetailPageURL;
				
				$medium_image_link = $res->Items->Item->MediumImage->URL;
				
				$small_image_link = $res->Items->Item->SmallImage->URL;
				
				$large_image_link = $res->Items->Item->LargeImage->URL;
				
				$this->Product->id = $pId['Product']['id'];
				$product_data = $this->Product->read();
				$updateProductData = array(
					'Product' => array(
						'link' => $order_link,
						'desc' => $product_feature,
						'small_image_link' => $small_image_link,
						'medium_image_link' => $medium_image_link,
						'large_image_link' => $large_image_link,
						'is_active' => 1
					)
				);
				$this->Product->save($updateProductData);
				
				unset($product_data);
				unset($updateProductData);
			}
			
		}die;
	}
	
	function updateSlug() {
		// Update category 
		$fields = array('Category.id', 'Category.name');
		$conditions = array('Category.slug IS NULL');
		$cats = $this->Category->find('all', array('fields' => $fields, 'conditions' => $conditions));
		$tmp = array();
		foreach($cats as $cat) {
			$slug = array(
				'Category' => array(
					'slug' => $this->toAscii($cat['Category']['name'])
				)				
			);
			$this->Category->id = $cat['Category']['id'];
			$this->Category->save($slug);
			unset($slug);
		}
		
		$fields = array('Product.id', 'Product.title');
		$conditions = array('Product.slug IS NULL');
		$ps = $this->Product->find('all', array('fields' => $fields, 'conditions' => $conditions));
		$tmp = array();
		foreach($ps as $p) {
			$slug = array(
				'Product' => array(
					'slug' => 'buy-cheap-' . $this->toAscii($p['Product']['title']) . 'on-black-friday-2012'
				)				
			);
			$this->Product->id = $p['Product']['id'];
			$this->Product->save($slug);
			unset($slug);
		}
		debug($tmp);die;
		// Update product
	}
	
	function toAscii($str, $replace=array(), $delimiter='-') {
		setlocale(LC_ALL, 'en_US.UTF8');
		if( !empty($replace) ) {
			$str = str_replace((array)$replace, ' ', $str);
		}

		$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
		$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
		$clean = strtolower(trim($clean, '-'));
		$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

		return $clean;
	}
	
	function generateTemplate($product, $productCat, $temp) {
		$incoming = array(
			'Buy <b> cheap ' . $product['Product']['title'] . " at Black Friday 2012 </b> on Amazon",
			//'<u> Cheap ' . $productCat['Category']['name'] . " at Black Friday 2012 on Amazon </u>",
			//'<i>Black Friday cheap ' . $product['Product']['title'] . '</i>',
			'Black Friday 2012 ' . $product['Product']['title'] . " sales price",
			//'Cheap ' . $productCat['Category']['name'] . ' Black Friday 2012',
			'Black Friday 2012 cheap ' . $productCat['Category']['name'],
			//'Amazon ' . $productCat['Category']['name'] . ' Black Friday 2012',
			$product['Product']['title']. " black friday 2012 deals",
			$product['Product']['title']. " black friday 2012 sales price",
			"Black Friday 2012 deals " . $product['Product']['title'],
		);
		if($this->Utils->isInCyberMonday($productCat['Category']['id'])) {
			$incoming[] = 'Buy <b> cheap ' . $product['Product']['title'] . " at Cyber Monday 2012 </b> on Amazon";
			//$incoming[] = '<u> Cheap ' . $productCat['Category']['name'] . " at Cyber Monday 2012 on Amazon </u>";
			//$incoming[] = '<u>' . $productCat['Category']['name'] . " at Cyber Monday 2012 deals </u>";
			$incoming[] = 'Cyber Monday 2012 deals ' . $productCat['Category']['name'];
		}
		$titles = array(
			"Buy cheap " . $product['Product']['title'] . " on Black Friday 2012",
			'Black Friday 2012 cheap ' . $product['Product']['title'],
			'Black Friday 2012 ' . $product['Product']['title'] . " sales",
			$product['Product']['title'] . " cheap on Amazon",
			"Cheap " . $product['Product']['title'] . " Black Friday 2012",
			"Black Friday 2012 " . $product['Product']['title'] . " sales price",
			"Black Friday 2012 discount " . $product['Product']['title'],
			"Discount " . $product['Product']['title'] . " Black Friday 2012",
			$product['Product']['title'] . " sales on Black Friday 2012",
			$product['Product']['title']. " black friday 2012 deals",
			"Black Friday 2012 deals " . $product['Product']['title'],
			"Black Friday 2012 sales " . $product['Product']['title'],
		);
		$title = $titles[array_rand($titles, 1)];
		$img = $product['Product']['large_image_link'];
		
		$html = "<div class='product'>";
		$html .= "<div class='product-image'> 
					<a rel='nofollow' href='" . $product['Product']['link'] . "' class='buy-link' value='" . $product['Product']['link'] . "'>
					<img src='" . $img . "' title='" . $title . "' alt='" . $title . "' />
					</a>"
				."</div>";
		$html .= "<div class='product-price'>"
				."<div class='product-rating'> 
						<span class='rating-" . $product['Product']['rating'] . "'>". $product['Product']['rating'] . " stars rating | 
						<a rel='nofollow' title='See more reviews' href='" . $product['Product']['reviews_link'] . "'> " . $product['Product']['reviews'] . " user reviews  </a> </span> 
					</div>"
				. "<p>List price: <span class='list-price'>" . $product['Product']['list_price'] . "</span></p>" 
				. "<p>Sale price: <span  class='price'>" . $product['Product']['sale_price'] . "</span></p>"
				. "<span class='saving'>You save: " . $product['Product']['savings'] . "</span>"
				. "<span class='discimg-" . round($product['Product']['saving_percent']) . "'></span>"
				."</div>";
		$html .= "<h3> Click to " . $title . " </h3>";
		$html .= "<div class='product-link'>"
				. "<a rel='nofollow' title='" . $title . "' alt='" . $title . "' href='". $product['Product']['link'] ."' class='buy-link' ></a>"
				. "</div>";
				
		$html .= "</hr><div class='product-desc'>" . "<h3>" . $product['Product']['title'] . " key features</h3>"				
					. $product['Product']['desc']
				."</div>";
		$html .= "<h3> Incoming search terms: </h3>";
		foreach($incoming as $term) {
			$html .= $term . "</br>";
		}
		$html .=  "</div>";
		
		return $html;
	}
	
	function post($product, $url, $maps, $temp = null) {
		$productCat = $this->Category->find('first', array('fields' => array('Category.id','Category.name'), 'conditions' => array('Category.id' => $product['Product']['category_id'])));
		// Prepare post
		
		$tag = array(
			//'Buy cheap ' . $productCat['Category']['name'] . ' Black Friday 2012',
			'Cheap ' . $productCat['Category']['name'] . ' Black Friday 2012',
			//'Black Friday 2012 cheap ' . $productCat['Category']['name'],
			'Black Friday 2012 ' . $productCat['Category']['name'],
			'Black Friday 2012 ' . $productCat['Category']['name'] . ' deals',
			'Black Friday 2012 sales ' . $productCat['Category']['name'],
			'Black Friday 2012 sales ' . $productCat['Category']['name'] . ' price',
			//'Amazon ' . $productCat['Category']['name'] . ' Black Friday 2012',
		);
		if($this->Utils->isInCyberMonday($productCat['Category']['id'])) {
			//$tag[] = 'Buy <b> cheap ' . $product['Product']['title'] . " at Cyber Monday 2012 </b> on Amazon";
			$tag[] = '<u> Cheap ' . $productCat['Category']['name'] . " at Cyber Monday 2012 on Amazon </u>";
			$tag[] = 'Cyber Monday 2012 cheap ' . $productCat['Category']['name'];
			$tag[] = 'Cyber Monday 2012 sales ' . $productCat['Category']['name'];
			$tag[] = 'Cyber Monday 2012 deals ' . $productCat['Category']['name'];
		}
		$postCat = array(
			$maps[$productCat['Category']['id']]
		);
		$html = $this->generateTemplate($product, $productCat, 1);
		
		/*$title = "Buy cheap " . $product['Product']['title'] . " at Black Friday 2012 on Amazon";
		$title = 'Black Friday cheap ' . $product['Product']['title'];
		$title = 'Black Friday ' . $product['Product']['title'] . " cheap on Amazon";
		$title = $product['Product']['title'] . " cheap on Amazon";
		$title = 'Buy ' . $product['Product']['title'] . " on Amazon";
		$title = $product['Product']['title'];*/
		$titles = array(
			"Buy cheap " . $product['Product']['title'] . " on Black Friday 2012",
			'Black Friday 2012 cheap ' . $product['Product']['title'],
			'Black Friday 2012 ' . $product['Product']['title'] . " sales",
			$product['Product']['title'] . " cheap on Amazon",
			"Cheap " . $product['Product']['title'] . " Black Friday 2012",
			"Black Friday 2012 " . $product['Product']['title'] . " sales price",
			"Black Friday 2012 discount " . $product['Product']['title'],
			"Discount " . $product['Product']['title'] . " Black Friday 2012",
			$product['Product']['title'] . " sales on Black Friday 2012",
			$product['Product']['title']. " black friday 2012 deals",
			"Black Friday 2012 deals " . $product['Product']['title'],
			"Black Friday 2012 sales " . $product['Product']['title'],
		);
		$title = $titles[array_rand($titles, 1)];
		$postData = array(
			'post' => array(
				'post_title'    => $title,
				'post_content'  => $html,
				'post_status'   => 'publish',
				'post_author'   => 1,
				'post_category' => $postCat,
				'tags_input' => $tag
			),
			'attachment' => array(
				'link' =>$product['Product']['large_image_link']
			)
		);
		// Post to wordpress
		//$postData = json_encode($postData);
		$opts = array(
			'http' => array (
				'method' => 'POST',
				'content' => http_build_query($postData),
				'header' => "Content-type: application/x-www-form-urlencoded\r\n"
			) 
		);
		
		//$context  = stream_context_create($opts);
		$ctx = stream_context_create($opts); 
		
		//$stream = @file_get_contents($url, false, $ctx);
		//var_dump($stream);die;
		//echo $url;die;
		//$url = 'http://kinectdancegames.net/post-product.php';
		
		$stream = fopen($url, 'r', false, $ctx); 
		
		// actual data at $url
		//var_dump(stream_get_contents($stream));die;
		
		if (!$stream) { 
		    throw new Exception("Problem with $url, $php_errormsg"); 
		} else {
			//var_dump($stream);
			fclose($stream);			
		}			
	}
	
	// Cheap Games US
	function postGames() {
		$url = 'http://cheapgamesus.com/post.php';
		
		$maps = array(
			'137' => '1',
			'138' => '3',
			'139' => '4',
			'140' => '5',
			'141' => '6',
			'142' => '7',
			'143' => '8',
			'144' => '9',
			'145' => '10',
			'146' => '11',
			'147' => '12',
			'148' => '13',
			'149' => '14',
			'150' => '15',
			'151' => '16',
			'152' => '17',
			'153' => '18',
			'154' => '19',
			'155' => '20',
			'156' => '21',
			'157' => '22',
			'158' => '23',
			'159' => '24',
			'160' => '25',
			'161' => '26',
			'162' => '27',
			'163' => '28',
			'164' => '29',
			'165' => '30',
			'166' => '31',
			'167' => '32',
			'168' => '33',
			'169' => '34',
		);
		
		$map = array_rand($maps, 1);
		$cats = $this->Utils->getSubCategory($map);
		
		$arr = array();
		
		foreach($cats as $cat) {
			$arr[] = $cat['Category']['id'];
		}
		
		//$index = rand(0, count($arr) -1);
		$catId = array_rand($arr, 1);
		// Get random product in Clothing
		$conditions = array('Product.category_id' => $catId, 'Product.is_active' => 1, 'Product.is_publish' => 0);
		$product = $this->Product->find('first', array('conditions' => $conditions, 'order' => 'rand()'));
		$url = 'http://cheapblackfriday2012.com';
		
		$this->post($product, $url, $maps);
	}
	
	function postUkGame() {
		$url = 'http://ukgame.net/post.php';
		
		$maps = array(
			'160' => '1',
			'161' => '3',
			'162' => '4',
			'163' => '5',
			'164' => '6',
			'165' => '7',
			'166' => '8',
			'167' => '9',
			'168' => '10',
			'169' => '11',
		);
		
		$cats = $this->Utils->getSubCategory(160);
		
		$arr = array();
		
		foreach($cats as $cat) {
			$arr[] = $cat['Category']['id'];
		}
		
		//$index = rand(0, count($arr) -1);
		$catId = array_rand($arr, 1);
		// Get random product in Clothing
		$conditions = array('Product.category_id' => $cats[$catId], 'Product.is_active' => 1, 'Product.is_publish' => 0);
		$product = $this->Product->find('first', array('conditions' => $conditions, 'order' => 'rand()'));
		
		$this->post($product, $url, $maps);
	}
	
	function postCheap() {
		$url = 'http://cheapblackfriday2012.com/post.php';
		
		$maps = array(
			'46' => '1', //Home and Garden
			'47' => '3',
			'48' => '4',
			'49' => '5',
			'50' => '6',
			'51' => '7',
			'52' => '8',
			'53' => '9',
			'54' => '10',
			'55' => '11',
			'56' => '12',
			'57' => '13',
			'58' => '14',
			'59' => '15',
			'75' => '16', // Kitchen
			'76' => '17',
			'77' => '18',
			'78' => '19',
			'79' => '20',
			'80' => '21',
			'81' => '22',
			'82' => '23',
			'83' => '24',
			'84' => '25',
			'85' => '26',
			'86' => '27',
			'87' => '28',
			'28' => '29', // Computer
			'29' => '29',
			'30' => '30',
			'31' => '31',
			'32' => '32',
			'33' => '33',
			'1' => '34', // Appliances
			'2' => '35',
			'3' => '36',
			'4' => '37',
			'5' => '38',
			'6' => '39',
			'7' => '40',
			'8' => '41',
			'9' => '42',
			'34' => '43', // Electronic
			'35' => '44',
			'36' => '45',
			'37' => '46',
			'38' => '47',
			'39' => '43',
			'40' => '48',
			'41' => '49',
			'42' => '50',
			'43' => '51',
			'44' => '52',
			'45' => '53',
			'60' => '54', // Home Improve
			'61' => '55',
			'62' => '56',
			'63' => '57',
			'64' => '58',
			'65' => '59',
			'66' => '60',
			'67' => '61',
			'68' => '62',
			'69' => '63',
			'70' => '64',
			'71' => '65',
			'72' => '66',
			'73' => '67',
			'74' => '68',
			'99' => '69', // Office Product
			'100' => '70',
			'101' => '71',
			'102' => '72',
			'103' => '73',
			'104' => '74',
			'105' => '75',
		);
		$tmp = array(46,75,28, 1, 34, 60, 99);
		$map = array_rand($tmp);
		$cats = $this->Utils->getSubCategory($tmp[$map]);
		
		$arr = array();
		
		foreach($cats as $cat) {
			$arr[] = $cat['Category']['id'];
		}
		
		//$index = rand(0, count($arr) -1);
		$catId = array_rand($arr);
		
		// Get random product in Clothing
		$conditions = array('Product.category_id' => $arr[$catId], 'Product.is_active' => 1, 'Product.is_publish' => 0);
		$product = $this->Product->find('first', array('conditions' => $conditions, 'order' => 'rand()'));
		//debug($product);die;
		//$url = 'http://cheapblackfriday2012.com';
		
		$this->post($product, $url, $maps);
	}
	
	function postKinect() {
		$url = 'http://kinectdancegames.net/post-product.php';
		
		$maps = array(
			'163' => '25',
			'164' => '26',
			'165' => '27',
			'166' => '28',
			'168' => '29',
			'136' => '123',
			'137' => '123',
			'138' => '123',
			'139' => '123',
			'140' => '123',
			'141' => '123',
			'142' => '123',
			'143' => '123',
			'144' => '123',
			'145' => '123',
			'146' => '123',
			'147' => '123',
			'148' => '123',
			'149' => '123',
			'150' => '123',
			'151' => '123',
			'152' => '123',
			'153' => '123',
			'154' => '123',
			'155' => '123',
			'156' => '123',
			'157' => '123',
			'158' => '123',
			'159' => '123',
		);
		
		$cats = $this->Utils->getSubCategory(136);
		
		$arr = array();
		
		foreach($cats as $cat) {
			$arr[] = $cat['Category']['id'];
		}
		//$arr = array(163,164,165,166,168);
		
		//$index = rand(0, count($arr) -1);
		$catId = array_rand($arr, 1);
		
		// Get random product in Clothing
		$conditions = array('Product.category_id' => $arr[$catId], 'Product.is_active' => 1, 'Product.is_publish' => 0);
		$product = $this->Product->find('first', array('conditions' => $conditions, 'order' => 'rand()'));
		//debug($product);die;
		$this->post($product, $url, $maps);die;
		
		// Update product is publish
		$productData = array(
			'Product' => array(
				'is_publish' => 1
			)
		);
		$this->Product->id = $product['Product']['id'];
		$this->Product->save($productData);
		die ('Sucess');	
	}
	
	function postEuzo() {
		$url = 'http://euzo.net/post-product.php';
		
		$maps = array(
			'46' => '1',
			/*'164' => '26',
			'165' => '27',
			'166' => '28',
			'168' => '29'*/
		);
		
		$cats = $this->Utils->getSubCategory(160);
		
		/*$arr = array();
		
		foreach($cats as $cat) {
			$arr[] = $cat['Category']['id'];
		}*/
		$arr = array(163,164,165,166,168);
		
		//$index = rand(0, count($arr) -1);
		$catId = array_rand($arr, 1);
		
		// Get random product in Clothing
		$conditions = array('Product.category_id' => 46, 'Product.is_active' => 1, 'Product.is_publish' => 0);
		$product = $this->Product->find('first', array('conditions' => $conditions, 'order' => 'rand()'));
		
		// Update product is publish
		$productData = array(
			'Product' => array(
				'is_publish' => 1
			)
		);
		$this->Product->id = $product['Product']['id'];
		$this->Product->save($productData);
		
		$this->post($product, $url, $maps);
		die ('Sucess');	
	}
	
	function postUsCooking() {
		$url = 'http://uscooking.net/post.php';
		
		$maps = array(
			'75' => '1', // Kitchen
			'76' => '3',
			'77' => '4',
			'78' => '5',
			'79' => '6',
			'80' => '7',
			'81' => '8',
			'82' => '9',
			'83' => '10',
			'84' => '11',
			'85' => '12',
			'86' => '13',
			'87' => '14',
		);
		
		$cats = $this->Utils->getSubCategory(75);
		
		$arr = array();
		
		foreach($cats as $cat) {
			$arr[] = $cat['Category']['id'];
		}
		
		//$index = rand(0, count($arr) -1);
		$catId = array_rand($arr, 1);
		// Get random product in Clothing
		$conditions = array('Product.category_id' => $catId, 'Product.is_active' => 1, 'Product.is_publish' => 0);
		$product = $this->Product->find('first', array('conditions' => $conditions, 'order' => 'rand()'));
		$url = 'http://cheapblackfriday2012.com';
		
		$this->post($product, $url, $maps, 1);
	}
	
	function postIpad() {
		$url = 'http://ipadpricedrop.us/post.php';
		
		$maps = array(
			'10' => '1', // Kitchen
			'11' => '3',
			'12' => '4',
			'13' => '5',
			'14' => '6',
			'15' => '7',
			'16' => '8',
			'17' => '9',
			'18' => '10',
			'19' => '9',
			'20' => '10'
		);
		$tmp = array(10,17);
		$cats = $this->Utils->getSubCategory($tmp[array_rand($tmp, 1)]);
		
		$arr = array();
		
		foreach($cats as $cat) {
			$arr[] = $cat['Category']['id'];
		}
		
		$index = rand(0, count($arr) -1);
		$catId = array_rand($arr, 1);
		// Get random product in Clothing
		$conditions = array('Product.category_id' => $arr[$catId], 'Product.is_active' => 1, 'Product.is_publish' => 0);
		$product = $this->Product->find('first', array('conditions' => $conditions, 'order' => 'rand()'));
		
		$this->post($product, $url, $maps);
	}
	
	function postLive() {
		$url = 'http://liveuro.net/post-product.php';
		$maps = array(
			'34' => '1', // Electronic
			'35' => '3',
			'36' => '4',
			'37' => '5',
			'38' => '6',
			'39' => '1',
			'40' => '7',
			'41' => '8',
			'42' => '9',
			'43' => '10',
			'44' => '11',
			'45' => '12',
		);
		
		$cats = $this->Utils->getSubCategory(34);
		
		$arr = array();
		
		foreach($cats as $cat) {
			$arr[] = $cat['Category']['id'];
		}
		
		$index = rand(0, count($arr) -1);
		$catId = array_rand($arr, 1);
		// Get random product in Clothing
		$conditions = array('Product.category_id' => $arr[$catId], 'Product.is_active' => 1, 'Product.is_publish' => 0);
		$product = $this->Product->find('first', array('conditions' => $conditions, 'order' => 'rand()'));
		
		$this->post($product, $url, $maps);
		
	}
}
?>